local skynet = require "skynet"
require "skynet.manager"	-- import skynet.register
local clientReady = {}
local playerName = {}
local playerStatus = {}
local playerPos = {}
local playerRot = {}
local playerMovement = {}

local command = {}

local players = {}
local name2id = {}

local max_actor_id = 0

-- function command.DEAD(id)
-- 	playerStatus[id] = "dead"
-- end

function command.REMOVE(id)
	local name = playerName[id]
	clientReady[id] = nil
	playerName[id] = nil
	playerStatus[id] = nil
	playerPos[id] = nil
	playerRot[id] = nil
	playerMovement[id] = nil
	return name
end

function command.GETCLIENTREADY()
	return clientReady
end

function command.UPDATE_PLAYER(id, key, value)
	if players[id] then
		players[id][key] = value
	end
end

function command.GET_PLAYERS()
	local online_players = {}
	for i,player in pairs(players) do
		skynet.error("player["..i .."] online:"..tostring(player.online))
		if players[i].online then
			online_players[i] = player
		end
	end
	return online_players
end

function command.GET_PLAYER(id)
	if players[id] then
		return players[id]
	end
	return nil
end

function command.LOGIN(player_name, player_password)
	local player_id = name2id[player_name]
	if player_id then
		if players[player_id].online then
			return -1	--用户已经登陆
		elseif players[player_id].password ~= player_password then
			return -2	--密码错误
		end
	end

	if player_id == nil then
		--产生一个新ID
		player_id = max_actor_id
		max_actor_id=max_actor_id+1
		name2id[player_name] = player_id
		print(">>>>>>>>>>>>>>")
		print(player_id, max_actor_id)

		local player = {
			id = player_id, 
			name = player_name, 
			password = player_password, 
			scene = 0,
			online = true,
			avatar = player_id % 4,
			pos = {math.random(-20,20), math.random(5,25), 40}
		}

		for i,v in pairs(player) do
			print(i,v)
		end
		players[player_id] = player
	else
		players[player_id].online = true
	end

	return player_id
end


function command.LOGOUT(player_id)
	skynet.error("logout:"..player_id)
	if players[player_id] then
		skynet.error("online:"..tostring(players[player_id].online))
		players[player_id].online = false
		skynet.error("online:"..tostring(players[player_id].online))
	end

	for id,player in pairs(players) do
		skynet.error("player["..id .."] online:"..tostring(player.online))
	end

end
skynet.start(function()
	skynet.dispatch("lua", function(session, address, cmd, ...)
		cmd = cmd:upper()
		if cmd == "PING" then
			assert(session == 0)
			local str = (...)
			if #str > 20 then
				str = str:sub(1,20) .. "...(" .. #str .. ")"
			end
			skynet.error(string.format("%s ping %s", skynet.address(address), str))
			return
		end
		local f = command[cmd]
		if f then
			skynet.ret(skynet.pack(f(...)))
		else
			error(string.format("Unknown command %s", tostring(cmd)))
		end
	end)
--	skynet.traceproto("lua", false)	-- true off tracelog
	skynet.register "SIMPLEDB"
end)